package com.yc.backstage.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.backstage.common.constant.UserConstants;
import com.yc.backstage.entity.SysDept;
import com.yc.backstage.entity.SysRole;
import com.yc.backstage.entity.SysUser;
import com.yc.backstage.entity.vo.QueryUserVo;
import com.yc.backstage.entity.vo.UpdateUserVo;
import com.yc.backstage.service.SysDeptService;
import com.yc.backstage.service.SysPostService;
import com.yc.backstage.service.SysRoleService;
import com.yc.backstage.service.SysUserService;
import com.yc.backstage.utils.SecurityUtils;
import com.yc.common.enums.BusinessType;
import com.yc.common.res.ResultClass;
import com.yc.common.utils.StringUtils;
import com.yc.logging.annotation.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname SysUserController
 * @Description
 * @Version 1.0.0
 * @Date 2022-08-23 11:49:19
 * @Created by Mikechen
 */
@RestController
@RequestMapping("/backstage/sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPostService sysPostService;
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 获取用户列表（分页）(按条件)
     */
    @PreAuthorize("@el.hasPermi('system:user:query')")
    @GetMapping("/list")
    public ResultClass list(QueryUserVo user) {
        Page<SysUser> sysUserPage = sysUserService.selectPage(user);
        return ResultClass.success(sysUserPage);
    }

    /**
     * 根据用户id获取详细信息
     */
    @PreAuthorize("@el.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public ResultClass getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        //检查是否有数据权限
        sysUserService.checkUserDataScope(userId);
        //获取角色集合
        List<SysRole> roles = sysRoleService.selectRoleAll();
        Map<String, Object> map = new HashMap<>();
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts", sysPostService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = sysUserService.selectUserById(userId);
            map.put("user", sysUser);
            map.put("postIds", sysPostService.selectPostIdsByUserId(userId));
            map.put("roleIds", sysRoleService.selectRoleIdsByUserId(userId));
        }
        return ResultClass.success(map);
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@el.hasPermi('system:dict:add')")
    @PostMapping("/add")
    public ResultClass add(@RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName()))) {
            return ResultClass.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return ResultClass.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {
            return ResultClass.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return ResultClass.success(sysUserService.insertUser(user));
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@el.hasPermi('system:user:update')")
    @PostMapping("/update")
    public ResultClass update(@Validated @RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        sysUserService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {
            return ResultClass.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {
            return ResultClass.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return ResultClass.success(sysUserService.updateUser(user));
    }

    /**
     * 根据id删除用户（可批量）
     *
     * @param ids
     * @return
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PreAuthorize("@el.hasPermi('system:user:remove')")
    @PostMapping("/remove")
    public ResultClass remove(@RequestBody List<Long> ids) {
        if (ids.contains(SecurityUtils.getUserId())) {
            return ResultClass.fail("当前用户不能删除");
        }
        return ResultClass.success(sysUserService.removeUserById(ids));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public ResultClass resetPwd(@RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        sysUserService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return ResultClass.success(sysUserService.resetPwd(user));
    }

    /**
     * 修改用户状态
     *
     * @param user
     * @return
     */
    @PreAuthorize("@el.hasPermi('system:user:update')")
    @PostMapping("/changeUserStatus")
    public ResultClass changeUserStatus(@RequestBody SysUser user) {
        sysUserService.checkUserAllowed(user);
        sysUserService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return ResultClass.success(sysUserService.updateUserStatus(user));
    }

    /**
     * 修改密码
     *
     * @return
     */
    @PreAuthorize("@el.hasPermi('system:user:update')")
    @PostMapping("/updatePassword")
    public ResultClass resetUserPwd(UpdateUserVo user) {
        sysUserService.updatePassword(user);
        return ResultClass.success();
    }


    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    @PreAuthorize("@el.hasPermi('system:user:query')")
    public ResultClass authRole(@PathVariable("userId") Long userId) {
        SysUser user = sysUserService.selectUserById(userId);
        List<SysRole> roles = sysRoleService.selectRolesByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ResultClass.success(map);
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public ResultClass insertAuthRole(Long userId, Long[] roleIds) {
        sysUserService.checkUserDataScope(userId);
        sysUserService.insertUserAuth(userId, roleIds);
        return ResultClass.success();
    }


    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public ResultClass deptTree(SysDept dept) {
        return ResultClass.success(sysDeptService.selectDeptTreeList(dept));
    }
}
